﻿
Partial Public Class cached_property_wrapper(Of T)
    Private initialized As Boolean = False
    Private last_write_ticks As Int64 = 0
    Private last_update_ticks As Int64 = 0
    Private d As T = Nothing

    Private Function update_ticks(ByRef i As Int64) As Boolean
        Return eva(i, Now.ticks())
    End Function

    Private Function update_last_write_ticks() As Boolean
        Return update_ticks(last_write_ticks)
    End Function

    Private Function update_last_update_ticks() As Boolean
        Return update_ticks(last_update_ticks)
    End Function

    Private Function should_write()
        Return last_write_ticks <= last_update_ticks
    End Function

    Private Sub initial_read()
        Dim result As pointer(Of T) = Nothing
        Dim ec As eventComb = Nothing
        assert_begin(New eventComb(Function() As Boolean
                                       result = New pointer(Of T)()
                                       ec = p.get_data(result)
                                       Return waitfor(ec) AndAlso
                                              goto_next()
                                   End Function,
                                   Function() As Boolean
                                       If ec.end_result() Then
                                           assert(Not +result Is Nothing)
                                           d = +result
                                       Else
                                           d = alloc(Of T)()
                                       End If
                                       Return eva(initialized, True) AndAlso
                                              goto_end()
                                   End Function))
    End Sub

    Private Sub start_write_back()
        assert_begin(New eventComb(Function() As Boolean
                                       Return waitfor(Function() initialized) AndAlso goto_next()
                                   End Function,
                                   Function() As Boolean
                                       Return waitfor(write_back_interval_ms) AndAlso
                                              goto_next()
                                   End Function,
                                   Function() As Boolean
                                       Return (Not should_write() OrElse
                                               (update_last_write_ticks() AndAlso
                                                waitfor(p.set_data(d)))) AndAlso
                                              goto_prev()
                                   End Function))
    End Sub

    Private Sub start()
        initial_read()
        start_write_back()
    End Sub
End Class
